// 轻量级定时任务
class MiniScheduler {
  constructor() {
    this.tasks = new Map();
    this.isRunning = false;
  }

  // 添加定时任务
  schedule(name, callback, interval) {
    this.tasks.set(name, {
      callback,
      interval,
      lastRun: 0,
      timer: null
    });
  }

  // 启动调度器
  start() {
    if (this.isRunning) return;
    
    this.isRunning = true;
    this.runTasks();
  }

  // 停止调度器
  stop() {
    this.isRunning = false;
    this.tasks.forEach(task => {
      if (task.timer) clearTimeout(task.timer);
    });
  }

  runTasks() {
    if (!this.isRunning) return;

    const now = Date.now();
    
    this.tasks.forEach((task, name) => {
      if (now - task.lastRun >= task.interval) {
        task.lastRun = now;
        
        // 执行任务
        Promise.resolve(task.callback()).catch(error => {
          console.error(`任务 ${name} 执行失败:`, error);
        });
      }
      
      // 设置下次检查
      task.timer = setTimeout(() => {
        this.runTasks();
      }, Math.min(task.interval, 60 * 1000)); // 最多每分钟检查一次
    });
  }
}

export const scheduler = new MiniScheduler()

// 添加任务
scheduler.schedule('初始化任务', () => {
  console.log("初始化任务")
}, 30 * 60 * 1000); // 每30分钟执行一次

